package com.bawei.image

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * Author: Jason Zhang
 * Date: 2025/4/24
 * Desc: 自定义Glide内存和磁盘缓存大小
 */

@GlideModule
class CustomGlideModule: AppGlideModule() {
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //1.修改内存缓存大小，默认内存大小当前APP内存大小1/8
        val memorySize = MemorySizeCalculator.Builder(context).build().memoryCacheSize / 6L
        builder.setMemoryCache(LruResourceCache(memorySize))

        //2.修改磁盘缓存大小，默认为250M
        builder.setDiskCache(InternalCacheDiskCacheFactory(context, "glide_disk_cache", 300 * 1024 * 1024))
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //创建Builder对象
        val builder = OkHttpClient.Builder()
        //外部SD卡的缓存目录
        val externalDir = Environment.getExternalStorageDirectory()
        var cacheDir = if(externalDir.exists()){
            "${externalDir.absolutePath}/cacheImage"
        } else{
            "${context.externalCacheDir?.absolutePath}/internal_cache_image" //内部SD卡的缓存目录
        }

        //创建缓存目录
        var cacheDirFile = File(cacheDir)
        if (!cacheDirFile.exists()){
            cacheDirFile =  File(cacheDir)
        }

        //计算缓存大小
        var cacheSize = 50 * 1024 * 1024L
        externalDir.totalSpace?.let{
            cacheSize = it / 8L
        }
        var networkCache = Cache(cacheDirFile, cacheSize)

        //设置缓存目录
        builder.cache(networkCache)
        val newOkHttpClient = builder.build()
        //替换网络缓存的客户端
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(newOkHttpClient))
    }









}